package cn.net.mugui.net.pc.panel.comp;

import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentLinkedDeque;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.MouseInputListener;

import org.apache.commons.lang3.StringUtils;

import com.mugui.Dui.DPanel;
import com.mugui.base.base.Autowired;
import com.mugui.base.base.Component;
import com.mugui.base.util.Other;
import com.sun.awt.AWTUtilities;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.net.mugui.net.pc.AutomaticChangeColor;
import cn.net.mugui.net.pc.bean.Barrage;
import cn.net.mugui.net.pc.bean.Fans_medalBean;
import cn.net.mugui.net.pc.bean.INTERACT_WORDBean;
import cn.net.mugui.net.pc.bean.NOTICE_MSGBean;
import cn.net.mugui.net.pc.panel.BilibiliPanel;

@SuppressWarnings("serial")
@Component
public class TMWindows extends DPanel {

	@Autowired
	AutomaticChangeColor autoTable;
	JPanel title_panel = null;

	public TMWindows() {
		setLayout(new BorderLayout(0, 0));

		title_panel = new JPanel();
		add(title_panel, BorderLayout.NORTH);

		JLabel lblNewLabel = new JLabel("弹幕");
		lblNewLabel.setForeground(Color.WHITE);
		lblNewLabel.setFont(new Font("宋体", Font.BOLD, 15));

		lblNewLabel.addMouseListener(l);
		lblNewLabel.addMouseMotionListener(l);
		title_panel.add(lblNewLabel);
		title_panel.setVisible(false);
		setBackground(null);
		setForeground(null);
		setOpaque(false);

//		JScrollPane scrollPane = new JScrollPane();
//		add(scrollPane, BorderLayout.CENTER);
//		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//		body_panel = new JPanel();
//		scrollPane.setViewportView(body_panel);
//		body_panel.setLayout(new DVerticalFlowLayout());
//		scrollPane.setBackground(null);
//		UiTool.全体透明(scrollPane);

	}

	public static Dimension win_size = Toolkit.getDefaultToolkit().getScreenSize();

	/**
	 * 1个弹幕消息
	 * 
	 * @param barrage
	 */
	public void addMsg(Barrage barrage) {
		if (graphics == null) {
			return;
		}
		TMUIBean tmuiBean = new TMUIBean() {

			@Override
			void action() {
				long time = System.currentTimeMillis() - this.getCreate_time();
				double x = (time - 12500) / 2500.0;
				int w = (int) (x * x / 1.5);
				if (w <= 4) {
					w = 4;
				}
				if (w > 50) {
					w = 50;
				}
				this.setX(getX() - w);
			}
		}.setX(selectX()).setY(selectY());
//		Fans_medalBean fans_medal = barrage.getFans_medal();
		LinkedList<TMUICompBean> linkedList = new LinkedList<>();
		tmuiBean.setComps(linkedList);
		if (StringUtils.isNotBlank(barrage.getMedal_anchor())) {
			String str = barrage.getMedal_name() + "[" + barrage.getMedal_level() + "]";
			int fontHeight = getFontHeight(graphics);
			int textLength = getTextLength(graphics, str);
			/**
			 * 粉丝牌子显示
			 */
			TMUICompBean compBean = new TMUICompBean(tmuiBean) {

				@Override
				void draw() {
					graphics.setComposite(AlphaComposite.SrcOver.derive(0.5f));
					graphics.setColor(Color.getColor("FFB6C1"));
					graphics.drawRect(getX() + tmuiBean.getX() - 2, getY() + tmuiBean.getY() - getHeight() + 2,
							getWidth() + 2, getHeight() + 4);
					graphics.setColor(Color.getColor("FFC0CB"));
					graphics.fillRect(getX() + tmuiBean.getX() - 2, getY() + tmuiBean.getY() - getHeight() + 2,
							getWidth() + 2, getHeight() + 4);
					graphics.setColor(Color.getColor("FF1493"));
					graphics.setComposite(AlphaComposite.SrcOver.derive(1f));
					graphics.drawString(str, getX() + tmuiBean.getX(), getY() + tmuiBean.getY());
				}
			}.setWidth(textLength).setHeight(fontHeight);
			linkedList.add(compBean);
		}

		String welcome = barrage.getUname() + ":" + barrage.getMsg();

		int fontHeight = getFontHeight(graphics);
		int textLength = getTextLength(graphics, welcome);
		/**
		 * 欢迎词显示
		 */
		TMUICompBean compBean = new TMUICompBean(tmuiBean) {

			@Override
			void draw() {
				int width_offset = 0;
				TMUICompBean tmuiCompBean = tmuiBean.getComps().get(0);
				if (tmuiCompBean != this) {
					width_offset = tmuiCompBean.getWidth();
				}
				graphics.setComposite(AlphaComposite.SrcOver.derive(0.5f));
				graphics.setColor(getBase());
				graphics.fillRect(getX() + tmuiBean.getX() + 2 + width_offset,
						getY() + tmuiBean.getY() - getHeight() + 2, getWidth() + 10, getHeight() + 4);
				graphics.setComposite(AlphaComposite.SrcOver.derive(1f));
				graphics.setColor(Color.white);
				graphics.drawString(welcome, getX() + tmuiBean.getX() + 6 + width_offset,
						getY() - 2 + tmuiBean.getY() + 2);
			}
		}.setWidth(textLength).setHeight(fontHeight).setBase(autoTable.getNowColor());
		linkedList.add(compBean);
//		if (RandomUtil.randomDouble() < 0.1)
		tmui_Beans.add(tmuiBean);

	}

	/**
	 * 加入欢迎动画
	 * 
	 * @param bean
	 */
	public void addMsg(INTERACT_WORDBean bean) {
		if (graphics == null) {
			return;
		}
		TMUIBean tmuiBean = new TMUIBean() {

			@Override
			void action() {
				long time = System.currentTimeMillis() - this.getCreate_time();
				double x = (time - 12500) / 2500.0;
				int w = (int) (x * x / 1.5);
				if (w <= 4) {
					w = 4;
				}
				if (w > 50) {
					w = 50;
				}
				this.setX(getX() - w);
			}
		}.setX(selectX()).setY(selectY());
		Fans_medalBean fans_medal = bean.getFans_medal();
		LinkedList<TMUICompBean> linkedList = new LinkedList<>();
		tmuiBean.setComps(linkedList);
		if (fans_medal.getAnchor_roomid() != 0) {
			String str = fans_medal.getMedal_name() + "[" + fans_medal.getMedal_level() + "]";
			int fontHeight = getFontHeight(graphics);
			int textLength = getTextLength(graphics, str);
			/**
			 * 粉丝牌子显示
			 */
			TMUICompBean compBean = new TMUICompBean(tmuiBean) {

				@Override
				void draw() {
					graphics.setComposite(AlphaComposite.SrcOver.derive(0.5f));
					graphics.setColor(new Color(fans_medal.getMedal_color_border()));
					graphics.drawRect(getX() + tmuiBean.getX() - 2, getY() + tmuiBean.getY() - getHeight() + 2,
							getWidth() + 2, getHeight() + 4);
					graphics.setColor(new Color(fans_medal.getMedal_color_start()));
					graphics.fillRect(getX() + tmuiBean.getX() - 2, getY() + tmuiBean.getY() - getHeight() + 2,
							getWidth() + 2, getHeight() + 4);
					graphics.setColor(getBase());
					graphics.setComposite(AlphaComposite.SrcOver.derive(1f));
					graphics.drawString(str, getX() + tmuiBean.getX(), getY() + tmuiBean.getY());
				}
			}.setWidth(textLength).setHeight(fontHeight).setBase(autoTable.getNowColor());
			linkedList.add(compBean);
		}

		String welcome = "欢迎[" + bean.getUname() + "]大佬进入";

		int fontHeight = getFontHeight(graphics);
		int textLength = getTextLength(graphics, welcome);
		/**
		 * 欢迎词显示
		 */
		TMUICompBean compBean = new TMUICompBean(tmuiBean) {

			@Override
			void draw() {
				int width_offset = 0;
				TMUICompBean tmuiCompBean = tmuiBean.getComps().get(0);
				if (tmuiCompBean != this) {
					width_offset = tmuiCompBean.getWidth();
				}
				graphics.setComposite(AlphaComposite.SrcOver.derive(0.5f));
				graphics.setColor(getBase());
				graphics.fillRect(getX() + tmuiBean.getX() + 2 + width_offset,
						getY() + tmuiBean.getY() - getHeight() + 2, getWidth() + 10, getHeight() + 4);
				graphics.setColor(Color.white);
				graphics.setComposite(AlphaComposite.SrcOver.derive(1f));
				graphics.drawString(welcome, getX() + tmuiBean.getX() + 6 + width_offset,
						getY() - 2 + tmuiBean.getY() + 2);
			}
		}.setWidth(textLength).setHeight(fontHeight).setBase(autoTable.getNowColor());
		linkedList.add(compBean);
//		if (RandomUtil.randomBoolean())
		tmui_Beans.add(tmuiBean);
	}

	/**
	 * 得到字宽
	 * 
	 * @param graphics
	 * @param text
	 * @return
	 */
	public static int getTextLength(Graphics graphics, String text) {
		return graphics.getFontMetrics().stringWidth(text);
	}

	/**
	 * 得到字高
	 * 
	 * @param graphics
	 * @return
	 */
	public static int getFontHeight(Graphics graphics) {
		return graphics.getFontMetrics().getAscent();
	}

	ConcurrentLinkedDeque<TMUIBean> tmui_Beans = new ConcurrentLinkedDeque<>();

	private int selectX() {
		return win_size.width;
	}

	int now_y = 0;
	int now_y_height = 40;
	int now_x = 0;
	long now_x_time = System.currentTimeMillis();

	private int selectY() {
		int now_y_ = now_y;
		now_y = now_y + now_y_height;
		if (now_y > image.getHeight() - 100) {
			now_y = 0;
		}
		return now_y_ + 40;
	}

	private float transparency = .0f;

	public void setTransparent(float transparency) {
		this.transparency = transparency;
	}

	BufferedImage image = null;
	/**
	 * 画笔
	 */
	Graphics2D graphics = null;

	public void createImage() {
		image = new BufferedImage(win_size.width, win_size.height / 2 + 200, BufferedImage.TYPE_INT_ARGB);

		graphics = (Graphics2D) image.getGraphics().create();
		graphics.setFont(new Font("黑体", Font.PLAIN, 21));
		graphics.setComposite(AlphaComposite.SrcOver.derive(transparency));
		graphics.setColor(autoTable.getNowColor());
		graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
	}

	@Autowired
	private BilibiliPanel panel;

	private MouseInputListener l = new MouseInputListener() {

		Point origin = new Point();

		@Override
		public void mouseReleased(MouseEvent e) {
		}

		@Override
		public void mousePressed(MouseEvent e) {
			// 鼠标按下
			origin.x = e.getX();
			origin.y = e.getY();

		}

		@Override
		public void mouseExited(MouseEvent e) {
			setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
		}

		@Override
		public void mouseEntered(MouseEvent e) {
			setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
		}

		@Override
		public void mouseClicked(MouseEvent e) {

		}

		@Override
		public void mouseDragged(MouseEvent e) {
			Point p = panel.getDialog().getLocation();
			panel.getDialog().setLocation(p.x + (e.getX() - origin.x), p.y + (e.getY() - origin.y));
			Other.sleep(20);
		}

		@Override
		public void mouseMoved(MouseEvent e) {

		}
	};

	static TMThread tmThread = null;

	public class TMThread extends Thread {

		boolean is_run = true;

		@Override
		public void run() {
			while (is_run) {
				repaint();
				int time = (int) (System.currentTimeMillis() - update_time);
				if (time < 25) {
					Other.sleep(25 - time);
				}
			}
		}

		public void close() {
			is_run = false;
		}
	}

	long update_time = System.currentTimeMillis();

	@Override
	public void paint(Graphics g) {
		// TODO Auto-generated method stub
		super.paint(g);
		paintTM();
		g.drawImage(image, 0, 30, null);
	}

	long time = System.currentTimeMillis();

	public void paintTM() {
		if (System.currentTimeMillis() - time > 5000) {
			panel.getDialog().setAlwaysOnTop(false);
			Other.sleep(10);
			panel.getDialog().setAlwaysOnTop(true);
			time = System.currentTimeMillis();
		}
		graphics.clearRect(0, 0, image.getWidth(), image.getHeight());
		graphics.dispose();
		graphics.finalize();
		createImage();
		graphics.setFont(new Font("微软雅黑", Font.PLAIN, 28));
		graphics.setComposite(AlphaComposite.SrcOver.derive(0.0f));
		graphics.setColor(Color.black);
		graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
		Iterator<TMUIBean> iterator = tmui_Beans.iterator();
		while (iterator.hasNext()) {
			TMUIBean next = iterator.next();
			if (System.currentTimeMillis() - next.getCreate_time() > 60000 || next.getX() < -1000) {
				iterator.remove();
			}
			Iterator<TMUICompBean> iterator2 = next.getComps().iterator();
			while (iterator2.hasNext()) {
				TMUICompBean next2 = iterator2.next();
				next2.draw();
			}
			next.action();
		}
		update_time=System.currentTimeMillis();
	}

//	@Override
//	public void paintAll(Graphics g) {
//		// TODO Auto-generated method stub
//		g.drawImage(image, 0, 30, null);
//		super.paintAll(g);
//	}

	@Override
	public void init() {
		createImage();
		AWTUtilities.setWindowOpaque(panel.getDialog(), false);
		panel.getDialog().setAlwaysOnTop(true);
		this.setBackground(null);
		if (tmThread == null || !tmThread.isAlive()) {
			autoTable.addNew(title_panel);
			tmThread = new TMThread();
			tmThread.start();
			System.out.println(tmThread.hashCode());
		}
	}

	@Override
	public void quit() {
		if (tmThread != null) {
			tmThread.close();
		}
	}

	@Override
	public void dataInit() {
		// TODO Auto-generated method stub

	}

	@Override
	public void dataSave() {
		// TODO Auto-generated method stub

	}

	/**
	 * 全区礼物
	 * 
	 * @param notice_MSGBean
	 */
	public void addMsg(NOTICE_MSGBean notice_MSGBean) {
		if (graphics == null) {
			return;
		}
		TMUIBean tmuiBean = new TMUIBean() {

			@Override
			void action() {
				long time = System.currentTimeMillis() - this.getCreate_time();
				double x = (time - 12500) / 2500.0;
				int w = (int) (x * x / 1.5);
				if (w <= 4) {
					w = 4;
				}
				if (w > 50) {
					w = 50;
				}
				this.setX(getX() - w);
			}
		}.setX(selectX()).setY(selectY());
		String string = notice_MSGBean.getFull().getString("head_icon_fa");
		notice_MSGBean.setLink_url(string);

		LinkedList<TMUICompBean> linkedList = new LinkedList<>();
		BufferedImage handleWebp = handleWebp(notice_MSGBean);
		notice_MSGBean.setImage(handleWebp);
		notice_MSGBean.setImage_size(notice_MSGBean.getFull().getInteger("head_icon_fan"));
		tmuiBean.setComps(linkedList);
		if (handleWebp != null) {
			/**
			 * 粉丝牌子显示
			 */
			TMUICompBean compBean = new TMUICompBean(tmuiBean) {

				@Override
				void draw() {
					graphics.setComposite(AlphaComposite.SrcOver.derive(1f));
					int now_show = notice_MSGBean.getNow_show();
					if (now_show >= notice_MSGBean.getImage_size()) {
						now_show = 0;
						notice_MSGBean.setNow_show(0);
					} else {
						notice_MSGBean.setNow_show(now_show + 1);
					}
					BufferedImage image = notice_MSGBean.getImage();

//					BufferedImage show=new BufferedImage(image.getHeight(), image.getHeight(),BufferedImage.TYPE_INT_ARGB);
//					Graphics graphics2 = show.getGraphics();
//					graphics2.clearRect(0, 0, 100, 100);
//					graphics2.drawImage(image, 0, 0,image.getHeight(),image.getHeight(), null);
//					graphics.clearRect(getX() + tmuiBean.getX(), getY() + tmuiBean.getY(), 100, 100);
//					graphics.drawImage(show, show.getHeight(), show.getWidth(), null);

					graphics.drawImage(image, getX() + tmuiBean.getX(), getY() + tmuiBean.getY(),
							getX() + tmuiBean.getX() + image.getHeight(), getY() + tmuiBean.getY() + image.getHeight(),
							now_show * image.getHeight(), 0, now_show * image.getHeight() + image.getHeight(),
							image.getHeight(), null);
				}
			}.setX(-75).setY(-75);
			linkedList.add(compBean);
		}

		String welcome = UnicodeUtil.toString(notice_MSGBean.getMsg_common());

		int fontHeight = getFontHeight(graphics);
		int textLength = getTextLength(graphics, welcome);
		/**
		 * 欢迎词显示
		 */
		TMUICompBean compBean = new TMUICompBean(tmuiBean) {

			@Override
			void draw() {
				int width_offset = 0;
				TMUICompBean tmuiCompBean = tmuiBean.getComps().get(0);
				if (tmuiCompBean != this) {
					width_offset = tmuiCompBean.getWidth();
				}
				graphics.setComposite(AlphaComposite.SrcOver.derive(0.5f));
				graphics.setColor(getBase());
				graphics.fillRect(getX() + tmuiBean.getX() + 2 + width_offset,
						getY() + tmuiBean.getY() - getHeight() + 2, getWidth() + 10, getHeight() + 4);
				graphics.setColor(Color.white);
				graphics.setComposite(AlphaComposite.SrcOver.derive(1f));
				graphics.drawString(welcome, getX() + tmuiBean.getX() + 6 + width_offset,
						getY() - 2 + tmuiBean.getY() + 2);
			}
		}.setWidth(textLength).setHeight(fontHeight).setBase(autoTable.getNowColor());
		linkedList.add(compBean);
		if (RandomUtil.randomBoolean())
			tmui_Beans.add(tmuiBean);
	}

	/**
	 * 处理图片
	 * 
	 * @param notice_MSGBean
	 * @return
	 */
	private BufferedImage handleWebp(NOTICE_MSGBean notice_MSGBean) {
		BufferedImage read = null;
		try {
			InputStream openStream = new URL(notice_MSGBean.getLink_url()).openStream();
			ImageInputStream createImageInputStream = ImageIO
					.createImageInputStream(openStream);
			read = ImageIO.read(createImageInputStream);
			openStream.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return read;
	}

}
